package com.example.utils;

import com.example.exception.TokenInvalidException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class IsValidToken {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void isValidToken(String responseBody) throws Exception {
        try {
            JsonNode jsonNode = objectMapper.readTree(responseBody);
            // 检查是否返回了错误信息
            if (jsonNode.has("error_code")) {
                String errorCode = jsonNode.get("error_code").asText();
                String errorMsg = jsonNode.get("error_msg").asText();
                if ("IOTDA.000004".equals(errorCode) && errorMsg.contains("Invalid access token")) {
                    throw new TokenInvalidException("Invalid access token");
                } else {
                    throw new Exception(errorMsg);
                }
            }
        } catch (Exception e) {
            throw new Exception("Failed to parse JSON response", e);
        }
    }
}
